/* -*- c++ -*- */
/*
 * Copyright 2004,2010 Free Software Foundation, Inc.
 *
 * This file is part of GNU Radio
 *
 * GNU Radio is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3, or (at your option)
 * any later version.
 *
 * GNU Radio is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with GNU Radio; see the file COPYING.  If not, write to
 * the Free Software Foundation, Inc., 51 Franklin Street,
 * Boston, MA 02110-1301, USA.
 */

/*
 * config.h is generated by configure.  It contains the results
 * of probing for features, options etc.  It should be the first
 * file included in your .cc file.
 */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#include <howto_spectrum_sensing_cf.h>
#include <gr_io_signature.h>
#include <math.h>
#include <stdio.h>

/*
 * Create a new instance of howto_square_ff and return
 * a boost shared_ptr.  This is effectively the public constructor.
 */
howto_spectrum_sensing_cf_sptr howto_make_spectrum_sensing_cf(float sample_rate, int ninput_samples, int nsub_bands, float pfd, float pfa, float tcme, bool debug_far,bool debug_stats)
{
  return gnuradio::get_initial_sptr(new howto_spectrum_sensing_cf (sample_rate, ninput_samples, nsub_bands, pfd, pfa, tcme, debug_far, debug_stats));
}

/*
 * Specify constraints on number of input and output streams.
 * This info is used to construct the input and output signatures
 * (2nd & 3rd args to gr_block's constructor).  The input and
 * output signatures are used by the runtime system to
 * check that a valid number and type of inputs and outputs
 * are connected to this block.  In this case, we accept
 * only 1 input and 1 output.
 */
static const int MIN_IN = 1;	// mininum number of input streams
static const int MAX_IN = 1;	// maximum number of input streams
static const int MIN_OUT = 1;	// minimum number of output streams
static const int MAX_OUT = 1;	// maximum number of output streams

/*
 * The private constructor
 */
howto_spectrum_sensing_cf::howto_spectrum_sensing_cf (float sample_rate, int ninput_samples, int nsub_bands, float pfd, float pfa, float Tcme, bool debug_far,bool debug_stats)
	: gr_sync_block ("spectrum_sensing_cf",
	  gr_make_io_signature (MIN_IN, MAX_IN, ninput_samples*sizeof (gr_complex)),
	  gr_make_io_signature (MIN_OUT, MAX_OUT, sizeof (float))),
	  d_sample_rate(sample_rate),
	  d_ninput_samples(ninput_samples),
 	  d_nsub_bands(nsub_bands),
	  d_pfd(pfd),
  	  d_pfa(pfa),
	  d_tcme(Tcme),
          d_trials_counter(0),
          d_false_alarm_counter(0),
          d_correct_rejection_counter(0),
          d_false_alarm_rate(0),
          d_correct_rejection_rate(0),
	  d_debug_far(debug_far), 
	  d_debug_stats(debug_stats)
{
	segment = new float[d_nsub_bands];
	sorted_segment = new float[d_nsub_bands];
}

/*
 * Our virtual destructor.
 */
howto_spectrum_sensing_cf::~howto_spectrum_sensing_cf ()
{
	delete[] segment;
	delete[] sorted_segment;
}

int
howto_spectrum_sensing_cf::work (int noutput_items,
			       gr_vector_const_void_star &input_items,
			       gr_vector_void_star &output_items)
{
  const gr_complex *in = (const gr_complex *) input_items[0];
  float *out = (float *) output_items[0];
	
  float zref, alpha, false_alarm_rate;
  int n_zref_segs = 0;

  for(int k=0;k<noutput_items;k++) {
	segment_spectrum(in, k);
	sort_energy();
	zref = calculate_noise_reference(&n_zref_segs);
	alpha = calculate_scale_factor(n_zref_segs);
	false_alarm_rate = calculate_statistics(alpha, zref, n_zref_segs);
	if(d_debug_far) printf("false_alarm_rate: %f\n",false_alarm_rate);
      	out[k] = false_alarm_rate;
  }

  // Tell runtime system how many output items we produced.
  return noutput_items;
}

/* Segment the spectrum into blocks with the sum of the energies.*/
bool howto_spectrum_sensing_cf::segment_spectrum(const gr_complex *in, int vector_number) {
	
	// d_nsub_bands must be a multiple of d_ninput_samples.
	assert(d_ninput_samples%d_nsub_bands == 0);
	
	int samples_per_band = d_ninput_samples/d_nsub_bands;
	
	for(int k=0;k<d_nsub_bands;k++) {
		segment[k] = 0.0;
		for(int i=0;i<samples_per_band;i++) {
			segment[k] = segment[k] + pow(abs(in[vector_number*d_ninput_samples + k*samples_per_band + i]),2);
		}
		sorted_segment[k] = segment[k];
	}
	return true;
}

/*This is the implemenatation of the algorithm proposed in reference [3]*/
bool howto_spectrum_sensing_cf::sort_energy() {
	float temp;

	//Sort Segmented PDP vector in increasing order of energy.
	for(int i=0;i<d_nsub_bands;i++) {
		for(int k=0;k<(d_nsub_bands-1);k++) {
			if(sorted_segment[k] > sorted_segment[k+1]) {
				temp = sorted_segment[k+1];
				sorted_segment[k+1] = sorted_segment[k];
				sorted_segment[k] = temp;
			}
		}
	}
	
	return true;
}

/* Algorithm used to discard samples. Indeed, it is used to find a speration between noisy samples and signal+noise samples.*/
float howto_spectrum_sensing_cf::calculate_noise_reference(int* n_zref_segs) {
	
	float limiar, energy[d_nsub_bands];
	int I = 0;
	
	for(I=20;I<d_nsub_bands;I++) {
		limiar = (float)(d_tcme/I);
		energy[I] = 0.0;
		for(int k=0;k<I;k++) {
			energy[I] = energy[I] + sorted_segment[k];
		}
		if(sorted_segment[I] > limiar*energy[I] || I==(d_nsub_bands-1)) {
			break;
		}
	}
	(*n_zref_segs) = I;
	return energy[I];
}

// Calculate the scale factor.
float howto_spectrum_sensing_cf::calculate_scale_factor(int x) {
	
	float value = 0.0;
	// Values caculated for M=16, Pfa=0.0001 and I varying from 1 to 128, i.e., (2048 points IFFT)/M.
	float a[] = {13.39, -10.29, 0.007391, 1.007e+12, 0.006561, 0.01239, 1.71e+10, 0.2332};
	float b[] = {-0.9831, -16.15, 26.53, -240.2, 27.85, 137.8, -73.25, -112.3};
	float c[] = {1.398, 12.08, 4.333, 46.41, 22.15, 59.77, 15.45, 125.3};
	
	value = a[0]*exp(-pow(((x-b[0])/c[0]),2));
	value = value + a[1]*exp(-pow(((x-b[1])/c[1]),2));
	value = value + a[2]*exp(-pow(((x-b[2])/c[2]),2));
	value = value + a[3]*exp(-pow(((x-b[3])/c[3]),2)); 
	value = value + a[4]*exp(-pow(((x-b[4])/c[4]),2)); 
	value = value + a[5]*exp(-pow(((x-b[5])/c[5]),2)); 
	value = value + a[6]*exp(-pow(((x-b[6])/c[6]),2));
	value = value + a[7]*exp(-pow(((x-b[7])/c[7]),2));
	
	return value;
}

float howto_spectrum_sensing_cf::calculate_statistics(float alpha, float zref, int I) {
	
	float ratio;
	
	for(int k=0;k<d_nsub_bands;k++) {
		d_trials_counter++;
		ratio = segment[k]/zref;
		
		if(ratio > alpha) {
			if(d_debug_stats) printf("ratio: %f - alpha: %f - segment[%d]: %f - zref: %f - I: %d\n",ratio,alpha,k,segment[k],zref,I);
			d_false_alarm_counter++;
		} else {
			d_correct_rejection_counter++;
		}
	}
	d_false_alarm_rate = (float)d_false_alarm_counter/d_trials_counter;
	d_correct_rejection_rate = (float)d_correct_rejection_counter/d_trials_counter;
	
	return d_false_alarm_rate;
}

/* REFERENCES

[1] Sesia, S., Baker, M., Toufik, I. - "LTE, the UMTS long term evolution: From theory to practice. Chichester", Wiley InterScience, 2009.
[2] 3GPP Technical Specification 36.213 - "Physical layer procedures (Release 10)", ww.3gpp.org.
[3] Jing Jiang, Muharemovic, Pierre Bertrand - "Random Access Preamble Detection for Long Term Evolution Wireless Networks", Patent number US 2009/0040918 A1.
[4] Fabbryccio A. C. Cardoso, Juliano João Bazzo, and Fabrício Lira Figueiredo, “Método de detecção de sinal primário para faixa de TV”, Caderno CPqD de Tecnologia.
*/

